package cn.gengar.domain.trade.service.lock.filter;

import cn.gengar.domain.trade.adapter.repository.ITradeRepository;
import cn.gengar.domain.trade.model.entity.GroupBuyActivityEntity;
import cn.gengar.domain.trade.model.entity.TradeRuleCommandEntity;
import cn.gengar.domain.trade.model.entity.TradeRuleFilterBackEntity;
import cn.gengar.domain.trade.service.lock.factory.TradeSettlementRuleFilterFactory;
import cn.gengar.types.design.framework.link.model2.handler.ILogicHandler;
import cn.gengar.types.enums.ActivityStatusEnumVO;
import cn.gengar.types.enums.ResponseCode;
import cn.gengar.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

@Slf4j
@Service
public class ActivityUsabilityRuleFilter implements ILogicHandler<TradeRuleCommandEntity, TradeSettlementRuleFilterFactory.DynamicContext, TradeRuleFilterBackEntity> {

    @Resource
    private ITradeRepository repository;

    @Override
    public TradeRuleFilterBackEntity apply(TradeRuleCommandEntity requestParameter, TradeSettlementRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
        log.info("交易规则过滤 - 活动可用性校验{} activityId:{}", requestParameter.getUserId(), requestParameter.getActivityId());

        GroupBuyActivityEntity groupBuyActivityEntity = repository.queryGroupBuyActivityByActivityId(requestParameter.getActivityId());

        if (Objects.isNull(groupBuyActivityEntity) || !ActivityStatusEnumVO.EFFECTIVE.equals(groupBuyActivityEntity.getStatus())) {
            throw new AppException(ResponseCode.E0101);
        }

        Date currentTime = new Date();
        if (currentTime.before(groupBuyActivityEntity.getStartTime()) || currentTime.after(groupBuyActivityEntity.getEndTime())) {
            throw new AppException(ResponseCode.E0102);
        }

        dynamicContext.setGroupBuyActivityEntity(groupBuyActivityEntity);
        return next(requestParameter, dynamicContext);
    }
}
